<template>
  <div class="page-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Calendar /></el-icon>
          <span>排考管理</span>
          <el-button 
            type="primary" 
            @click="scheduleExams"
            :loading="scheduling"
            :disabled="!hasData"
          >
            <el-icon><Star /></el-icon>
            智能排考
          </el-button>
        </div>
      </template>

      <div v-if="!hasData" class="no-data">
        <el-empty description="请先添加教师和考试信息" />
      </div>

      <div v-else>
        <!-- 统计信息 -->
        <div v-if="scheduleStats" class="stats-container">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-statistic title="总出行次数" :value="scheduleStats.totalTrips" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="最大监考次数" :value="scheduleStats.maxAssignments" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="最小监考次数" :value="scheduleStats.minAssignments" />
            </el-col>
            <el-col :span="6">
              <el-statistic title="监考次数差值" :value="scheduleStats.assignmentDifference">
                <template #suffix>
                  <el-tag :type="scheduleStats.assignmentDifference <= 2 ? 'success' : 'warning'">
                    {{ scheduleStats.assignmentDifference <= 2 ? '符合要求' : '超出要求' }}
                  </el-tag>
                </template>
              </el-statistic>
            </el-col>
          </el-row>
        </div>

        <!-- 排考结果 -->
        <div v-if="assignments.length > 0" class="assignments-container">
          <h3>排考结果</h3>
          <el-table 
            :data="groupedAssignments" 
            style="width: 100%"
            stripe
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          >
            <el-table-column prop="examName" label="考试名称" min-width="150" />
            <el-table-column prop="examTime" label="考试时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.examTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="teacherNames" label="监考教师" min-width="300">
              <template #default="scope">
                <el-tag 
                  v-for="teacher in scope.row.teacherNames" 
                  :key="teacher"
                  style="margin-right: 5px; margin-bottom: 5px;"
                  effect="plain"
                >
                  {{ teacher }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="teacherCount" label="监考人数" width="100">
              <template #default="scope">
                <el-tag type="success">{{ scope.row.teacherCount }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 教师监考统计 -->
        <div v-if="teacherStats.length > 0" class="teacher-stats">
          <h3>教师监考统计</h3>
          <el-table 
            :data="teacherStats" 
            style="width: 100%"
            stripe
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          >
            <el-table-column prop="name" label="教师姓名" width="120" />
            <el-table-column prop="employeeId" label="工号" width="100" />
            <el-table-column prop="assignmentCount" label="监考次数" width="100">
              <template #default="scope">
                <el-tag :type="getAssignmentCountType(scope.row.assignmentCount)">
                  {{ scope.row.assignmentCount }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="exams" label="监考考试" min-width="300">
              <template #default="scope">
                <el-tag 
                  v-for="exam in scope.row.exams" 
                  :key="exam"
                  style="margin-right: 5px; margin-bottom: 5px;"
                  size="small"
                  effect="plain"
                >
                  {{ exam }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Calendar, Star } from '@element-plus/icons-vue'
import { scheduleApi } from '@/api/schedule'
import { teacherApi } from '@/api/teacher'
import { examApi } from '@/api/exam'

interface Assignment {
  examId: number
  examName: string
  examTime: string
  teachers: number[]
  teacherNames: string[]
}

interface ScheduleStats {
  maxAssignments: number
  minAssignments: number
  assignmentDifference: number
  totalTrips: number
  objectiveValue: number
}

interface TeacherStat {
  name: string
  employeeId: string
  assignmentCount: number
  exams: string[]
}

const assignments = ref<Assignment[]>([])
const scheduleStats = ref<ScheduleStats | null>(null)
const teacherStats = ref<TeacherStat[]>([])
const scheduling = ref(false)
const teachers = ref([])
const exams = ref([])

const hasData = computed(() => {
  return teachers.value.length > 0 && exams.value.length > 0
})

const groupedAssignments = computed(() => {
  return assignments.value.map(assignment => ({
    ...assignment,
    teacherCount: assignment.teacherNames.length
  }))
})

const formatDateTime = (dateTime: string) => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const getAssignmentCountType = (count: number) => {
  if (!scheduleStats.value) return ''
  
  const { maxAssignments, minAssignments } = scheduleStats.value
  if (count === maxAssignments) return 'danger'
  if (count === minAssignments) return 'success'
  return 'primary'
}

const loadData = async () => {
  try {
    const [teacherData, examData] = await Promise.all([
      teacherApi.getTeachers(),
      examApi.getExams()
    ])
    teachers.value = teacherData
    exams.value = examData
  } catch (error) {
    ElMessage.error('加载数据失败')
  }
}

const scheduleExams = async () => {
  if (!hasData.value) {
    ElMessage.warning('请先添加教师和考试信息')
    return
  }

  scheduling.value = true
  try {
    const result = await scheduleApi.scheduleExams()
    assignments.value = result.assignments
    scheduleStats.value = result.stats
    
    // 计算教师统计
    calculateTeacherStats()
    
    ElMessage.success('排考完成')
  } catch (error: any) {
    ElMessage.error(error.message || '排考失败')
  } finally {
    scheduling.value = false
  }
}

const calculateTeacherStats = () => {
  const stats: { [key: number]: TeacherStat } = {}
  
  // 初始化统计
  teachers.value.forEach((teacher: any) => {
    stats[teacher.id] = {
      name: teacher.name,
      employeeId: teacher.employee_id,
      assignmentCount: 0,
      exams: []
    }
  })
  
  // 统计监考次数和考试
  assignments.value.forEach(assignment => {
    assignment.teachers.forEach(teacherId => {
      if (stats[teacherId]) {
        stats[teacherId].assignmentCount++
        stats[teacherId].exams.push(assignment.examName)
      }
    })
  })
  
  teacherStats.value = Object.values(stats).sort((a, b) => {
    return parseInt(b.employeeId) - parseInt(a.employeeId)
  })
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.page-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 10px;
  justify-content: space-between;
}

.header-icon {
  color: #409EFF;
  font-size: 18px;
}

.no-data {
  text-align: center;
  padding: 40px;
}

.stats-container {
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 8px;
  border-left: 4px solid #409EFF;
}

.assignments-container {
  margin-bottom: 30px;
}

.teacher-stats h3 {
  margin-bottom: 20px;
  color: #409EFF;
}

h3 {
  margin-bottom: 20px;
  color: #409EFF;
  font-size: 18px;
  font-weight: 600;
}

:deep(.el-table) {
  background-color: transparent;
}

:deep(.el-table tr) {
  background-color: transparent;
}

:deep(.el-table--striped .el-table__body tr.el-table__row--striped td) {
  background-color: rgba(0, 0, 0, 0.02);
}

:deep(.el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

:deep(.el-statistic__content) {
  font-size: 24px;
  font-weight: 600;
}

:deep(.el-statistic__head) {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
</style>
